package com.dizner.diassistant.ui.dashboard

import android.app.DatePickerDialog
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import com.dizner.diassistant.R
import com.dizner.diassistant.database.AppDatabase
import com.dizner.diassistant.database.DBOptionManager
import com.dizner.diassistant.dataentry.BloodPressureHistoryEntry
import kotlinx.android.synthetic.main.fragment_dashboard.*
import java.text.SimpleDateFormat
import java.util.*
import android.widget.DatePicker
import android.app.TimePickerDialog


class DashboardFragment : Fragment(), View.OnClickListener {
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_submit -> {
                commitHistory()
            }
            else -> {
            }
        }
    }

    private val TAG: String = "DashboardFragment"
    private lateinit var dashboardViewModel: DashboardViewModel

    private lateinit var appDatabase: AppDatabase

    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        dashboardViewModel =
            ViewModelProviders.of(this).get(DashboardViewModel::class.java)
        val root =
            inflater.inflate(com.dizner.diassistant.R.layout.fragment_dashboard, container, false)

        appDatabase = AppDatabase.getInstance(context!!)

        return root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()

    }

    private fun initView() {
        btn_submit.setOnClickListener(this)
        btn_submit.isEnabled = false
        et_input_value_1.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                btn_submit.isEnabled =
                    !TextUtils.isEmpty(et_input_value_1.text) && !TextUtils.isEmpty(et_input_value_2.text) && !TextUtils.isEmpty(
                        et_input_value_3.text
                    )
            }

        })
        et_input_value_2.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                btn_submit.isEnabled =
                    !TextUtils.isEmpty(et_input_value_1.text) && !TextUtils.isEmpty(et_input_value_2.text) && !TextUtils.isEmpty(
                        et_input_value_3.text
                    )
            }

        })
        et_input_value_3.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                btn_submit.isEnabled =
                    !TextUtils.isEmpty(et_input_value_1.text) && !TextUtils.isEmpty(et_input_value_2.text) && !TextUtils.isEmpty(
                        et_input_value_3.text
                    )
            }

        })

        tv_input_value_3.setOnClickListener {
            val ca = Calendar.getInstance()
            var mYear = ca.get(Calendar.YEAR)
            var mMonth = ca.get(Calendar.MONTH)
            var mDay = ca.get(Calendar.DAY_OF_MONTH)

            var timeStr = StringBuilder()

            var timePickerDialog = TimePickerDialog(
                context!!,
                TimePickerDialog.OnTimeSetListener { view, hourOfDay, minute ->
                    if (hourOfDay > 9) {
                        timeStr.append(hourOfDay.toString())
                    } else {
                        timeStr.append("0")
                        timeStr.append(hourOfDay.toString())
                    }
                    timeStr.append(":")
                    if (minute > 9) {
                        timeStr.append(minute.toString())
                    } else {
                        timeStr.append("0")
                        timeStr.append(minute.toString())
                    }
                    timeStr.append(":")
                    timeStr.append("00")
                    val time = timeStr.toString()
                    tv_input_value_3.text = time
                },
                9,
                0,
                true
            )

            val datePickerDialog = DatePickerDialog(
                context!!,
                DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
                    mYear = year
                    mMonth = month
                    mDay = dayOfMonth + 1

                    timeStr.append(mYear.toString())
                    timeStr.append("-")
                    if (mMonth > 9) {
                        timeStr.append(mMonth.toString())
                    } else {
                        timeStr.append("0")
                        timeStr.append(mMonth.toString())
                    }
                    timeStr.append("-")

                    if (mDay > 9) {
                        timeStr.append(mDay.toString())
                    } else {
                        timeStr.append("0")
                        timeStr.append(mDay.toString())
                    }
                    timeStr.append(" ")
                    timePickerDialog.show()
                    toast(timeStr.toString())
                },
                mYear, mMonth, mDay
            )
            datePickerDialog.show()
        }

    }


    private fun commitHistory() {

        if (TextUtils.isEmpty(et_input_value_1.text)) {
            toast("请输入高压")
            return
        }

        if (TextUtils.isEmpty(et_input_value_2.text)) {
            toast("请输入低压")
            return
        }
        if (TextUtils.isEmpty(et_input_value_3.text)) {
            toast("请输入心率")
            return
        }

        var higher = et_input_value_1.text.toString().toInt()
        var lower = et_input_value_2.text.toString().toInt()
        var heartRate = et_input_value_3.text.toString().toInt()


        var entry = BloodPressureHistoryEntry(higher, lower, heartRate, dateFormat.format(Date()))

        DBOptionManager.instance.executeDBOption(appDatabase.getHistoryDao()
            .addNewHistory(entry),
            object : DBOptionManager.Callback<Long>() {
                override fun onSuccess(data: Long?) {
                    toast("添加成功")
                    et_input_value_1.setText("")
                    et_input_value_2.setText("")
                    et_input_value_3.setText("")
                }

                override fun onFailure(error: Throwable) {
                    toast("添加失败")
                }
            })

//


    }

    private fun toast(toastMsg: String) {
        Toast.makeText(context, toastMsg + "", Toast.LENGTH_SHORT).show()
    }
}